import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Table, Select, Popconfirm, Image, Cascader } from 'antd';
import usePageAccess from '@/components/usePageAccess';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryZhaoMuListParams, ZhaoMu } from './services';
import { ZhaoMuStatus, queryZhaoMuList, delZhaoMu, PowerStatus, LockStatus, ZhaoMuGround } from './services'
import { enum2options } from '@/utils/enum2options';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import { StationParkType } from '@/pages/station/stationList/services';
import { queryCityOptions2 } from '@/services/common';
import { styled } from '@umijs/max';
import { jump2target } from '@/utils/common';

const LinkInfoContainer = styled.div`
  width: max-content;
  border-radius: 8px;
  background: #f5f5f5;
  padding: 0 16px;
`
const LinkInfoItem = styled.div`
  width: 100%;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eeeeee;

  .label {
    width: 100px;
  }

  .value {
  }
`

const ZhaoMuPage: React.FC = () => {
  const access = usePageAccess()
  const cityOptions = useRequest(queryCityOptions2)
  const [searchForm] = Form.useForm<QueryZhaoMuListParams>()
  const [searchParams, setSearchParams] = useState<QueryZhaoMuListParams>({
    pageNum: 1, pageSize: 10,
  })
  const zhaoMuList = useRequest(() => queryZhaoMuList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: delZhaoMuAsync } = useRequest(delZhaoMu, {manual: true})

  const openEditPage = (title: string, type: string, employeeId?: number) => {
    jump2target(`/zhaoMu/edit?type=${type}&id=${employeeId || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/zhaoMu/edit_title', title)
  }

  const onFinish = (formValues: QueryZhaoMuListParams) => {
    setSearchParams({
      ...searchParams,
      ...formValues,
      cityId: formValues.cityId?.at(-1),
      pageNum: 1,
    })
  }

  const columns: ColumnsType<ZhaoMu> = [
    {
      title: '电站名称',
      width: 200,
      dataIndex: 'stationName',
    },
    {
      title: '小区名称',
      width: 200,
      dataIndex: 'houseName',
    },
    {
      title: '地址',
      width: 200,
      dataIndex: 'address',
    },
    {
      title: '联系方式',
      width: 'max-content',
      dataIndex: 'linkInfo',
      render: linkInfo => {
        const _linkInfo = JSON.parse(linkInfo)
        if (_linkInfo.linkInfo) {
          const keys = Object.keys(_linkInfo.linkInfo)
          return <LinkInfoContainer>
            {
              keys.map((key) => {
                return <LinkInfoItem key={key}>
                  <div className="label">{ key }</div>
                  <div className='value'>
                    <div>手机号：{_linkInfo.linkInfo[key].telephone || (_linkInfo.linkInfo[key] as any)}</div>
                    <div>
                      <span>客服二维码：</span>
                      {
                        _linkInfo.linkInfo[key].qrCode ? <img src={_linkInfo.linkInfo[key].qrCode} style={{width: 60, height: 60}} /> : '--'
                      }
                    </div>
                  </div>
                </LinkInfoItem>
              })
            }
          </LinkInfoContainer>
        }
      }
    },
    {
      title: '直流桩数',
      width: 120,
      dataIndex: 'stubOneNum',
    },
    {
      title: '交流桩数',
      width: 120,
      dataIndex: 'stubTwoNum',
    },
    {
      title: '充电车位数量',
      width: 140,
      dataIndex: 'chargeNum',
    },
    {
      title: '占地面积(m²)',
      width: 140,
      dataIndex: 'placeArea',
    },
    {
      title: '投资金额',
      width: 120,
      dataIndex: 'infoMoney',
    },
    {
      title: '分成比例',
      width: 120,
      key: 'scale',
      render: (_, record) => {
        const _linkInfo = JSON.parse(record.linkInfo)
        return `${_linkInfo.scale}%`
      }
    },
    {
      title: '合作期限',
      width: 120,
      key: 'hzqx',
      render: (_, record) => {
        const _linkInfo = JSON.parse(record.linkInfo)
        return _linkInfo.hzqx
      }
    },
    {
      title: '状态',
      width: 120,
      dataIndex: 'status',
      render: status => status && ZhaoMuStatus[status]
    },
    {
      title: '电表状态',
      width: 120,
      dataIndex: 'powerStatus',
      render: powerStatus => powerStatus && PowerStatus[powerStatus]
    },
    {
      title: '地锁状态',
      width: 120,
      dataIndex: 'lockStatus',
      render: lockStatus => lockStatus && LockStatus[lockStatus]
    },
    {
      title: '场地类型',
      width: 120,
      dataIndex: 'ground',
      render: ground => ground && ZhaoMuGround[ground]
    },
    {
      title: '停车收费',
      width: 120,
      dataIndex: 'parkType',
      render: parkType => parkType && StationParkType[parkType]
    },
    {
      title: '添加时间',
      width: 140,
      dataIndex: 'createTime',
      render: createTime => dayjs(createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '修改时间',
      width: 140,
      dataIndex: 'updateTime',
      render: updateTime => updateTime ? dayjs(updateTime).format('YYYY-MM-DD HH:mm:ss') : '--'
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 200,
      fixed: 'right',
      render: (id: number) => {
        return <Space>
          <a onClick={() => openEditPage('编辑', 'edit', id)}>编辑</a>
          <Popconfirm
            title={`确定删除吗?`}
            onConfirm={() => delZhaoMuAsync({stationId: id}).then(zhaoMuList.refresh)}
            okText="删除"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      zhaoMuList.refresh()
    }
    window.addEventListener('refreshZhaoMuList', refresh)
    return () => {
      window.removeEventListener('refreshZhaoMuList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <Access accessible={!!access.add || true}>
          <div className="toolbar">
            <Space>
              <Button type='primary' onClick={() => openEditPage('添加场站', 'edit')}>添加场站</Button>
            </Space>
          </div>
        </Access>
        <div className="form-area">
          <Form name='searchZhaoMuForm' form={searchForm} onFinish={onFinish} initialValues={{cityId:['320000', '321300', '321323']}}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='关键词' name='keyword'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='城市' name='cityId'>
                  <Cascader
                    loading={cityOptions.loading}
                    options={cityOptions.data?.data}
                    style={{width: '100%'}}
                    placeholder='请选择'
                    changeOnSelect
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='停车费用' name='parkPayType'>
                  <Select placeholder='请选择' options={enum2options(StationParkType)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='状态' name='status'>
                  <Select placeholder='请选择' options={enum2options(ZhaoMuStatus)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='地锁状态' name='lockStatus'>
                  <Select placeholder='请选择' options={enum2options(LockStatus)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={zhaoMuList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<ZhaoMu>
          rowKey='id'
          loading={zhaoMuList.loading}
          dataSource={zhaoMuList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: zhaoMuList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
    </div>
  );
};

export default ZhaoMuPage;
